import os, os.path, pdb
import SconsUtils.utils as utils
from functools import partial
import subprocess

Import('env')

nenv = env.Clone()

BOUND_FILES = Split("""
              #include/aff4_internal.h
              #include/aff4_constants.h
              #include/aff4_utils.h
              #include/aff4_rdf.h
              #include/aff4_io.h
              #include/aff4_resolver.h
              #include/aff4_rdf_serialise.h
              #include/aff4_objects.h
              #include/aff4_crypto.h
""")

if utils.HEADERS.get("HAVE_LIBEWF_H"):
    BOUND_FILES.append("#include/ewfvolume.h")

import class_parser

def build_python_bindings(target, source, env, initialization='',
                          free='aff4_free',
                          current_error_function='aff4_get_current_error'):
    """ A command to generate python bindings """
    try:
        target, public_api, public_header = target
    except:
        target = target[0]

    module_name = os.path.splitext(os.path.basename(target.name))[0]
    utils.warn("Generating automatic python bindings for module %s" % module_name)

    ## Sets the free function
    class_parser.FREE = free
    p = class_parser.HeaderParser(module_name, verbose=env['V'])
    p.module.init_string = initialization
    try:
        p.module.public_header = open(public_header.path, 'w')
        p.module.public_api = open(public_api.path, 'w')
    except: pass

    p.parse_filenames([s.get_abspath() for s in source])

    fd = open(target.get_abspath(), 'w')
    p.write(fd)
    fd.close()

    try:
        p.module.public_header.close()
        p.module.public_api.close()
    except: pass

nenv.Append(CFLAGS = " -include lib/config.h -Ilibraptor ")

if not nenv.get("disable_curl"):
    BOUND_FILES.append("#include/aff4_http.h")

if 1:
    nenv.Command(['pyaff4.c', '#lib/public.c', '#include/aff4_public.h'],
                 BOUND_FILES, partial(build_python_bindings,
                                      initialization='',
                                      current_error_function = 'aff4_get_current_error'))
    nenv.Depends('pyaff4.c', 'class_parser.py')
    nenv.PythonModule("pyaff4", ["pyaff4.c"], LIBS=env.libaff4_so)

    ## Keep this around for debian package
    env.python_aff4_env = nenv

if utils.HEADERS.get('HAVE_TSK3') and nenv.config.TSK3_HEADER_LOCATION:
    nenv = env.Clone()

    BOUND_FILES = Split("""
    %(TSK3_HEADER_LOCATION)s/libtsk.h
    %(TSK3_HEADER_LOCATION)s/fs/tsk_fs.h
    %(TSK3_HEADER_LOCATION)s/base/tsk_base.h
    %(TSK3_HEADER_LOCATION)s/img/tsk_img.h
    tsk/tsk3.h
    """ % nenv.config.__dict__)

    nenv.Append(CFLAGS = " -I %(TSK3_HEADER_LOCATION)s " % nenv.config.__dict__)

    nenv.Command(['tsk/pytsk3.c'], BOUND_FILES, partial(build_python_bindings,
                                                        initialization='tsk_init();',
                                                        current_error_function = 'aff4_get_current_error',
                                                        free = 'talloc_free'))
    nenv.Depends('tsk/pytsk3.c', 'class_parser.py')
    error_lib = nenv.SharedObject(
        source = "#lib/error.c", target='shared_error',
        CFLAGS=nenv.python_cppflags + '-Ilibreplace/ -Ilib/ -O0 -g'.split())

    nenv.PythonModule("pytsk3", ['tsk/pytsk3.c', 'tsk/tsk3.c', error_lib], LIBS=['tsk3'])

    # Keep this around for debian package
    env.python_tsk3_env = nenv

if 0 and utils.HEADERS.get('HAVE_REGFI') and nenv.config.REGFI_HEADER_LOCATION:
    nenv = env.Clone()

    BOUND_FILES = Split("""
    %(REGFI_HEADER_LOCATION)s/regfi.h
    regfi/pyregfi.h
    """ % nenv.config.__dict__)

    nenv.Append(CFLAGS = " -I %(REGFI_HEADER_LOCATION)s " % nenv.config.__dict__)

    nenv.Command('regfi/pyregfi.c', BOUND_FILES, partial(build_python_bindings,
                                                         initialization='pyregfi_init();'))
    nenv.Depends('regfi/pyregfi.c', 'class_parser.py')

    nenv.PythonModule("pyregfi", ['regfi/pyregfi.c', 'regfi/regfi.c'], LIBS=[env.libaff4_so, 'regfi'])

    # Keep this around for debian package
    env.python_regfi_env = nenv
